using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace CustomDialogs
{
    public class MultiFolderDialog : Form
    {
        // 选中的文件夹列表
        public List<string> SelectedFolders { get; private set; } = new List<string>();

        // 对话框标题
        public string Title { get; set; } = "选择多个文件夹";

        // 提示文本
        public string Description { get; set; } = "请勾选需要选择的文件夹:";

        private TreeView folderTree;
        private Label lblDescription;
        private Button btnOk;
        private Button btnCancel;
        private CheckBox chkSelectSubfolders;

        public MultiFolderDialog()
        {
            InitializeComponents();
            LoadDrives();
        }

        private void InitializeComponents()
        {
            // 基础设置
            this.Text = Title;
            this.Size = new Size(600, 500);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 描述标签
            lblDescription = new Label
            {
                Text = Description,
                Dock = DockStyle.Top,
                Padding = new Padding(10, 10, 10, 5),
                AutoSize = false,
                Height = 30
            };

            // 文件夹树视图
            folderTree = new TreeView
            {
                Dock = DockStyle.Fill,
                CheckBoxes = true,
                ShowLines = true,
                ShowPlusMinus = true,
                ShowRootLines = true,
                PathSeparator = Path.DirectorySeparatorChar.ToString()
            };
            folderTree.AfterCheck += FolderTree_AfterCheck;
            folderTree.BeforeExpand += FolderTree_BeforeExpand;

            // 全选子文件夹选项
            chkSelectSubfolders = new CheckBox
            {
                Text = "勾选文件夹时自动选择所有子文件夹",
                Dock = DockStyle.Top,
                Padding = new Padding(10, 5, 10, 5),
                AutoSize = true,
                Checked = true
            };

            // 按钮面板
            Panel buttonPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 50,
                Padding = new Padding(10)
            };

            // 确定按钮
            btnOk = new Button
            {
                Text = "确定",
                DialogResult = DialogResult.OK,
                Size = new Size(80, 30),
                Location = new Point(buttonPanel.ClientSize.Width - 180, 10)
            };

            // 取消按钮
            btnCancel = new Button
            {
                Text = "取消",
                DialogResult = DialogResult.Cancel,
                Size = new Size(80, 30),
                Location = new Point(buttonPanel.ClientSize.Width - 90, 10)
            };

            // 组装控件
            buttonPanel.Controls.Add(btnOk);
            buttonPanel.Controls.Add(btnCancel);

            this.Controls.Add(folderTree);
            this.Controls.Add(chkSelectSubfolders);
            this.Controls.Add(lblDescription);
            this.Controls.Add(buttonPanel);

            // 注册关闭事件
            this.FormClosing += MultiFolderDialog_FormClosing;
        }

        // 加载所有可用驱动器
        private void LoadDrives()
        {
            try
            {
                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    if (drive.IsReady)
                    {
                        TreeNode driveNode = new TreeNode(drive.Name)
                        {
                            Tag = drive.RootDirectory.FullName,
                            ImageIndex = 0,
                            SelectedImageIndex = 0
                        };
                        folderTree.Nodes.Add(driveNode);
                        // 添加占位符节点，用于延迟加载
                        driveNode.Nodes.Add(new TreeNode());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载驱动器失败: {ex.Message}", "错误", 
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 节点展开时加载子目录
        private void FolderTree_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            TreeNode currentNode = e.Node;
            
            // 只处理带有占位符的节点
            if (currentNode.Nodes.Count == 1 && currentNode.Nodes[0].Tag == null)
            {
                currentNode.Nodes.Clear();
                
                try
                {
                    string[] subDirectories = Directory.GetDirectories(currentNode.Tag.ToString());
                    foreach (string dir in subDirectories)
                    {
                        TreeNode dirNode = new TreeNode(Path.GetFileName(dir))
                        {
                            Tag = dir
                        };
                        currentNode.Nodes.Add(dirNode);
                        // 添加占位符
                        dirNode.Nodes.Add(new TreeNode());
                    }
                }
                catch
                {
                    // 忽略无权限访问的文件夹
                }
            }
        }

        // 处理复选事件
        private void FolderTree_AfterCheck(object sender, TreeViewEventArgs e)
        {
            // 防止递归调用导致的问题
            if (e.Action != TreeViewAction.Unknown && chkSelectSubfolders.Checked)
            {
                CheckAllChildNodes(e.Node, e.Node.Checked);
            }
        }

        // 递归勾选/取消勾选所有子节点
        private void CheckAllChildNodes(TreeNode node, bool check)
        {
            foreach (TreeNode childNode in node.Nodes)
            {
                childNode.Checked = check;
                if (childNode.Nodes.Count > 0)
                {
                    CheckAllChildNodes(childNode, check);
                }
            }
        }

        // 收集选中的文件夹
        private void CollectSelectedFolders()
        {
            SelectedFolders.Clear();
            CollectFoldersRecursive(folderTree.Nodes);
        }

        // 递归收集选中的文件夹
        private void CollectFoldersRecursive(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Checked && node.Tag != null)
                {
                    SelectedFolders.Add(node.Tag.ToString());
                }
                if (node.Nodes.Count > 0)
                {
                    CollectFoldersRecursive(node.Nodes);
                }
            }
        }

        // 对话框关闭时收集结果
        private void MultiFolderDialog_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                CollectSelectedFolders();
            }
        }

        // 显示对话框的静态方法
        public static List<string> ShowDialog1(string description = null)
        {
            using (MultiFolderDialog dialog = new MultiFolderDialog())
            {
                if (!string.IsNullOrEmpty(description))
                {
                    dialog.Description = description;
                }
                //MultiFolderDialog.ShowDialog("xxxx");
                //return null;
                return dialog.ShowDialog() == DialogResult.OK ? dialog.SelectedFolders : new List<string>();
            }
        }
    }
}
